package com.congapp.util;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class ObtenerPosicion implements LocationListener {

    private static final ObtenerPosicion instance;

    static {
        try {
            instance = new ObtenerPosicion();
        } catch (Exception e) {
            throw new RuntimeException("error iniciando los botones sociales", e);
        }
    }

    public static ObtenerPosicion getInstance() {
        return instance;
    }

    private ObtenerPosicion() {
    }
    
    private LocationManager locationManager;
    private Location location;
    private String provider;
    private long minTime = 5 * 1000; // Minimum time interval for update in seconds, i.e. 5 seconds.
    private long minDistance = 10; // Minimum distance change for update in meters, i.e. 10 meters.

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onLocationChanged(Location location) {
        this.location = location;
    }

    public Location getLocation(LocationManager locationManager) {
        if(locationManager != null && this.locationManager == null) {
            this.locationManager = locationManager;
            Criteria criteria = new Criteria();
            provider = locationManager.getBestProvider(criteria, false);
            // Assign LocationListener to LocationManager in order to receive location updates.
            // Acquiring provider that is used for location updates will also be covered later.
            // Instead of LocationListener, PendingIntent can be assigned, also instead of
            // provider name, criteria can be used, but we won't use those approaches now.
            locationManager.requestLocationUpdates(provider, minTime, minDistance, this);
            location = locationManager.getLastKnownLocation(provider);
        }
        return location;
    }
}
